import ReactDOM from 'react-dom';
import React from 'react';
import {asyncComponent} from 'react-async-component';
import {Bubble, Modal, Toast, Tools, WhiteSpace, WingBlank} from 'weaver-mobile';
import {isEmpty, isObject} from 'lodash';

import * as pageTypes from "../constants/OdocPageType";
import * as odocRequestAPI from "../apis/odocRequest/index";
import {initSignApprovalFloatDom, queryUrlString, showConfirm} from './CommonUtil';
import jQuery from "jquery";

const alert = Modal.alert;

const getLabel = Tools.getLabel;

const WfForm = window.WfForm;
const RequestRightBtn = window.rightBtn;

const coms = {
    OdocPages: asyncComponent({
        resolve: () => import('../components/OdocPages2Workflow')
    })
}

export default class OdocRightBtn4Export {
    constructor() {
        this.setBase = this.setBase.bind(this);
        this.getWorkflowStores = this.getWorkflowStores.bind(this);
        this.clearCheckEvent = this.clearCheckEvent.bind(this);
        this.safeExecuteFunc = this.safeExecuteFunc.bind(this);
        this.updateLastOperateInfo = this.updateLastOperateInfo.bind(this);
        this.doSaveWorkflow = this.doSaveWorkflow.bind(this);
        this.doOdocTransfer = this.doOdocTransfer.bind(this);
        this.pushEventList = this.pushEventList.bind(this);
        this.triggerEvent = this.triggerEvent.bind(this);

        /**
         * 如果页面加载完成后就触发的事件，请在此处调用pushEventList，将需要执行的事件加入到待执行事件列表中
         */
        this.pushEventList(() => {
            this.clear4RequestEvent();
        });

        //加载多语言标签
        Tools.getLocaleLabel("odoc", () => {
            console && console.log("加载公文多语言标签成功...");
            this.bindCustomTabEvent();
            this.showSignApproval();
        });

        this.firstTabKeyItem = {};
    }

    /**
     * 流程模块中的src4js/mobile4mobx/workflowForm/util/base.js，
     * 存储下来方便获取到流程中的store
     */
    base = {};

    /**
     * 上一次注册的事件的下标
     */
    lastEventIndex = -1;

    /**
     * 页面加载后需要触发的事件
     */
    eventList = [];

    /**
     * 页面中tab页显示组件的
     */
    containerInForm = null;

    setBase(val) {
        this.base = val;

        /**
         *  src4js/mobile4mobx/workflowForm/util/formBtnUtil.js中会调用setBase方法，
         *  此时已经能取到流程的store，可以触发公文需要执行的事件了
         */
        this.triggerEvent();
    }

    pushEventList(fn) {
        if (typeof fn == "function") {
            if (this.eventList && this.eventList instanceof Array) {
                this.eventList.push(fn);
            } else {
                fn();
            }
        }
    }

    triggerEvent() {
        const workflowStores = this.getWorkflowStores();
        const {wfGlobalStore} = workflowStores;
        const {commonParam} = wfGlobalStore;

        if (isEmpty(commonParam)) {     //说明流程还未加载完毕
            console && console.log("流程未加载完毕...");
            window.setTimeout(() => {
                this.triggerEvent();
            }, 300)
        } else {
            console && console.log("执行公文初始化事件...");
            if (this.eventList && this.eventList instanceof Array) {
                this.eventList.map(fn => fn());
                this.eventList = null;      //置空，表示已经执行过
            }
        }
    }

    getWorkflowStores() {
        const {allStores} = this.base;
        const {wfGlobalStore, wfLayoutStore, wfOperateStore, wfSignListStore, wfSignInputStore} = allStores;
        return {wfGlobalStore, wfLayoutStore, wfOperateStore, wfSignListStore, wfSignInputStore};
    }

    clearCheckEvent() {
        //说明存在上次注册的事件，先删除上次注册的事件
        if (this.lastEventIndex != -1) {
            const eventList = WfForm.eventList[WfForm.OPER_CLOSE];
            const newList = [];
            if (eventList != null && eventList.length > 0) {
                for (var i = 0; i < eventList.length; i++) {
                    if (i != this.lastEventIndex) {
                        newList.push(eventList[i]);
                    }
                }
            }

            WfForm.eventList[WfForm.OPER_CLOSE] = newList;
            this.lastEventIndex = -1;
        }

        /**
         * 还原之前的操作，避免标准的操作，比如保存流程会出现问题
         */
        const workflowStores = this.getWorkflowStores();
        const {wfOperateStore} = workflowStores;
        wfOperateStore.changeSubmitParam({isOdocRequest: "0"});
    }

    safeExecuteFunc(fun, funParam) {
        fun && typeof fun == "function" && fun(funParam);
    }

    updateLastOperateInfo(requestid, callback) {
        const workflowStores = this.getWorkflowStores();
        const {wfOperateStore} = workflowStores;

        odocRequestAPI.getLastOperateInfo({requestid}).then(data => {
            wfOperateStore.changeSubmitParam(data);
            this.safeExecuteFunc(callback);
        })
    }

    /**
     * 当点击的是流程的流转按钮时，清除为了公文流转而注册的事件
     */
    clear4RequestEvent = () => {
        const $this = this;
        const clearEventFn = (callback, funcParams = {}) => {
            //点击的不是公文流转的按钮，清除注册的事件
            if (!$this.isOdocEvent(funcParams)) {
                $this.clearCheckEvent();
            }

            callback();
        }

        //注册流程表单按钮点击的钩子事件
        WfForm.registerCheckEvent(WfForm.OPER_BEFORECLICKBTN, clearEventFn);
    }

    /**
     * 是否点击的公文流转事件
     */
    isOdocEvent = (menuItem) => {
        if (!isEmpty(menuItem) && isObject(menuItem)) {
            const {menuFun, type} = menuItem;
            if (type.indexOf("BTN_CUSTOMIZE") != -1 && menuFun.indexOf("OdocRightBtn.") != -1) {
                return true;
            }
        }

        return false;
    }

    /**
     * 保存流程表单，但是不刷新表单
     * @param callbackFn
     * @param isSubmit
     */
    doSaveWorkflow(callbackFn, isSubmit = false) {
        const workflowStores = this.getWorkflowStores();
        const {wfGlobalStore, wfOperateStore} = workflowStores;

        const checkEvent = (callback, funcParams = {}) => {
            const {isReturn = false} = funcParams;
            if (isReturn) {       //EM7中点击左上角的返回按钮
                callback();
            }

            Toast.hide();       //表单操作条关闭
            wfOperateStore.controllBottomBtnDisable(false);     //流程表单上的按钮置为可用

            const {commonParam} = wfGlobalStore;
            const {submitParam} = wfOperateStore;

            //刷新submit_token，避免流程会拦截重复提交
            const {workflowid, f_weaver_belongto_userid} = commonParam;
            const {requestid} = submitParam;
            const submitTokenKey = f_weaver_belongto_userid + "_" + requestid + "_request_submit_token";
            const param = {
                [submitTokenKey]: "",
                iscreate: "0"
            };

            wfOperateStore.changeSubmitParam(param);

            this.updateLastOperateInfo(requestid, () => {
                if (callbackFn && typeof callbackFn == "function") {
                    //callback参数是function，如果需要继续关闭窗口，就请在callbaclFn中执行完异步请求后，调用此方法
                    callbackFn(callback, funcParams);
                }
            });
        }

        //先清除之前注册的事件
        this.clearCheckEvent();

        //注册保存成功后关闭流程表单的事件
        WfForm.registerCheckEvent(WfForm.OPER_CLOSE, checkEvent);

        //记录下最新加入的事件的下标
        const eventList = WfForm.eventList[WfForm.OPER_CLOSE];
        if (eventList != null && eventList.length > 0) {
            this.lastEventIndex = eventList.length - 1;
        }

        //执行流程保存操作
        wfOperateStore.changeSubmitParam({isOdocRequest: "1"});
        //RequestRightBtn.doSave_nNew();
        /**
         *  改为提交的目的，是为了保证，公文添加的拦截事件，比如验证套红、正文是否保存等可以生效，
         *  服务端会拦截，将参数修改为保存，以达到仅保存流程，而不流转的目的
         */
        if (isSubmit) {
            RequestRightBtn.doSubmitBack();
        } else {
            RequestRightBtn.doSave_nNew();
        }
    }

    registerEmSDKEvent = () => {
        let _that = this;
        let {requestid = -1, nodeid, workflowid, f_weaver_belongto_userid, f_weaver_belongto_usertype} = window.WfForm.getGlobalStore().commonParam;
        let isEm = window.navigator.userAgent.indexOf("E-Mobile7") >= 0;
        let params = {
            requestid,
            nodeid,
            workflowid,
            isem: isEm ? 1 : 0,
            f_weaver_belongto_userid,
            f_weaver_belongto_usertype,
            islock: 1
        }
        odocRequestAPI.isSeal(params).then(data => {
            window.WebViewJavascriptBridge.registerHandler('wellSign', function (data1, responseCallback) {
                if(window.console){
                  console.log("--------好签接口类型:"+data1.type);
                }
                if (data1.type == "flow_submit") {
                    WfForm.doRightBtnEvent("BTN_SUBBACKNAME");
                    WfForm.doRightBtnEvent("BTN_SUBMIT");
                } else if (data1.type == "flow_reject") {
                    WfForm.doRightBtnEvent("BTN_REJECTNAME");
                } else if (data1.type == "closed") {
                    _that.doCheckSignApprovalFile(requestid, 2, data.userid);
                }

                //处理相关逻辑
                let responseData = {'Javascript Says': 'Right back atcha!'};
                //回调数据给客户端
                responseCallback(responseData)
            })
            let wellSignData = {
                ...data.wellSign,
                params: {
                    f_weaver_belongto_userid: f_weaver_belongto_userid,
                    f_weaver_belongto_usertype: f_weaver_belongto_usertype
                }
            }
            window.em.invoke('wellSign', {
                'wellSign': wellSignData,
                success: function () {

                }
            })
        });
    }

    goSignApprovalPage = (data) => {
        let {device = "H5", wellSign = {}} = data;
        let _that = this;
        if (device == "H5") {
            const comType = pageTypes.ODOC_SIGN_APPROVAL;
            const dialogType = 1;

            const state = {dialogType, comType, title: ""};
            const workflowStores = this.getWorkflowStores();
            //点击取消的回调
            const onClose = () => {
                this.clearCheckEvent();
            }
            window.historyRoute.push({
                pathname: "/req/odocComs",
                state,
                workflowStores,
                onClose
            });
        } else {
            if (window.WebViewJavascriptBridge && window.em) {
                if (window.em.checkJsApi("wellSign")) {
                    _that.registerEmSDKEvent();
                } else {
                    Bubble.warning(getLabel('523377', '当前设备不支持好签SDK服务'), 2);
                }
            }
        }

    }

    doCheckSignApprovalFile = (requestid, type, userid) => {
        let {f_weaver_belongto_userid, f_weaver_belongto_usertype} = WfForm.getGlobalStore().commonParam;
        if (window.fetch) {
            window.fetch("/api/odoc/hq/checkSeal2?requestid=" + requestid + "&checktype=" + type + "&userid=" + userid + "&f_weaver_belongto_userid=" + f_weaver_belongto_userid + "&f_weaver_belongto_usertype=" + f_weaver_belongto_usertype + "&xxc=1", {
                method: "GET",
                keepalive: true
            })
        } else {
            odocRequestAPI.checkSeal({
                requestid: requestid,
                checktype: type,
                userid: userid,
                f_weaver_belongto_userid,
                f_weaver_belongto_usertype,
                keepalive: true,
                xxc: 2
            }).then(data => {
            })
        }
    }

    showSignApproval = () => {
        let isEm = window.navigator.userAgent.indexOf("E-Mobile7") >= 0;
        let _that = this;
        let timer = setInterval(function () {
			let {commonParam={}} = WfForm.getGlobalStore();
            let {requestid = -1, nodeid=-1, workflowid=-1, f_weaver_belongto_userid=-1, f_weaver_belongto_usertype=0} = commonParam;
            if (requestid > 0) {
                clearInterval(timer);
                let params = {
                    requestid,
                    nodeid,
                    workflowid,
                    isem: isEm ? 1 : 0,
                    islock: 1,
                    f_weaver_belongto_userid,
                    f_weaver_belongto_usertype
                };
                odocRequestAPI.isSeal(params).then(data => {
                    if (data.api_status && data.api_status == 1) {
                        if (data.isView && data.isView == true) {
                            let oDiv = document.getElementById('haoqian');
                            if (!oDiv) {
                                jQuery("#root").append("<div id='haoqian' style='width: 90px;height: 30px;position: fixed;z-index:99;" +
                                    "background-color: #4878D3;line-height: 30px;text-align: center;color: #fff;'><div>" + getLabel('521681', "文件签批") + "</div></div>");
                            }
                            initSignApprovalFloatDom(document.getElementById('haoqian'), _that.goSignApprovalPage, {
                                ...data,
                                signDeviceType: isEm ? 0 : 1
                            });
                            if (data.isOpen && data.isOpen == true) {
                                setTimeout(function () {
                                    _that.goSignApprovalPage(data);
                                }, 500);
                                // let timer1 = setInterval(function () {
                                //     //等到底部按钮展示出来再进行跳转，否则有可能会导致底部按钮未隐藏的情况
                                //     if(jQuery(".wf-req-bottom .sign-bottom-item").length>0){
                                //         clearInterval(timer1);
                                //
                                //     }
                                // })
                            }
                            if (data.isSeal && data.isSeal == true) {
                                window.onbeforeunload = function () {
                                    _that.doCheckSignApprovalFile(requestid, 2, data.userid);
                                };
                                let intervalTime = parseInt(data.recheckoutminute) * 60000 || 600000;
                                setInterval(function () {
                                    //文档签出
                                    _that.doCheckSignApprovalFile(requestid, 1, data.userid);
                                }, intervalTime);
                            }
                        }
                    } else if (data.api_status != 1) {
                        Toast.fail(data.msg || "获取数据失败", 1);
                    }

                    if (data.isMust && data.isMust == true) {
                        WfForm.registerCheckEvent(WfForm.OPER_SUBMIT, function (callback) {
                            odocRequestAPI.hasSeal(params).then(data1 => {
                                if (data1.api_status && data1.api_status == 1) {
                                    if (data1.hasSeal && data1.hasSeal == true) {
                                        callback();
                                    } else {
                                        let signApprovalCtx = window.signApprovalCtx;
                                        if (signApprovalCtx) {
                                            signApprovalCtx.CloseWrite();
                                            if (signApprovalCtx.CheckoutHasUnsaveData()) {
                                                //保存操作
                                                window.signApprovalCtx.SimulateClickBtn("wsSaveBtn");
                                                setTimeout(function () {
                                                    callback();
                                                }, 1000)
                                            } else {
                                                Bubble.error(data1.msg || getLabel('521680', '签批未完成'), 1);
                                            }
                                        } else {
                                            Bubble.error(data1.msg || getLabel('521680', '签批未完成'), 1);
                                        }
                                    }
                                } else {
                                    Bubble.error(data1.msg, 1);
                                }
                            })
                        })
                    }
                })
            }
        }, 500)

    }


    getNewCusTabs(oldTabs, customTabs, notOdocCusTabs) {
        let newCusTabs = [];
        customTabs.forEach(item => {
            if (item.tabType == 0) {
                if (oldTabs.indexOf(item.key) >= 0) {
                    newCusTabs.push(item);
                }
            } else {
                newCusTabs.push(item);
            }
            if (newCusTabs.length > 0) {
                this.firstTabKeyItem = newCusTabs[0];
            }
        })
        return [...newCusTabs, ...notOdocCusTabs];
    }

    /**
     * 移动端自定义tab页签事件绑定
     */
    bindCustomTabEvent() {
        let _that = this;
        let customTabsArray = [];
        const {requestid = "", workflowid = ""} = queryUrlString();
        let params = {
            workflowid,
            requestid
        }
        odocRequestAPI.getOdocTabManagerDatas(params).then(data => {
            if (data.api_status && data.api_status == true) {
                let customTabs = data.customTabs;
                let isDefaultOpenOdoc = data.isDefaultOpenOdoc||false;
                if (customTabs.length > 0) {
                    WfForm.registerAction(WfForm.ACTION_TABCONFIG, function (tabDatas) {
                        let notOdocCusTabs = tabDatas.filter(item => item.key.indexOf("custom_iframe") >= 0)
                        let oldTabsArr = tabDatas.filter(item => item.key.indexOf("custom_iframe") < 0).map(item => item.key);
                        return _that.getNewCusTabs(oldTabsArr, customTabs, notOdocCusTabs);
                    });
                    if(isDefaultOpenOdoc==true||requestid==""||requestid<1){
                      //正文默认打开不作处理
                    }else {
                      let timer = setInterval(function () {
                        if (WfForm.getBaseInfo && WfForm.getBaseInfo().workflowid && WfForm.getBaseInfo().workflowid > 0) {
                          let {key,type} = _that.firstTabKeyItem;
                          if(type==1){
                            WfForm.getGlobalStore().setTabKey(key);
                          }
                          WfForm.switchTab(key,type);
                          clearInterval(timer);
                        }
                      }, 500)
                    }


                    customTabs.map(item => {
                        let key = item.key;
                        let type = item.type;
                        customTabsArray.push(key);
                        if (key.indexOf("custom_iframe_workflowCusTab_") >= 0) {
                            window.WfForm.bindCustomTabEvnent(key, function () {
                                _that.fnTabClick(key, item);
                            });
                        }
                    })
                }

            }
        }).then(data => {
            if (customTabsArray.length > 0) {
                WfForm.registerAction(WfForm.ACTION_SWITCHTAB, function (toTab, fromTab) {
                    if (customTabsArray.indexOf(fromTab) >= 0 && customTabsArray.indexOf(toTab) < 0) {
                        jQuery("#odoc_custab_box").css({display: "none"})
                        jQuery(".custom-tab-iframe").css({display: "block"})
                    } else if (customTabsArray.indexOf(toTab) >= 0) {
                        jQuery("#odoc_custab_box").css({display: "block", height: "100%"})
                        jQuery(".wf-append-iframe").css({height: "100%"})
                        jQuery(".custom-tab-iframe").css({display: "none"})
                    }
                })
            }
        })
    }

    fnTabClick = (key, item) => {
        const comType = pageTypes.ODOC_CHANGE_ODOC_CUS_TAB;
        const dialogType = 1;

        const state = {dialogType, comType, ...item};
        const workflowStores = this.getWorkflowStores();
        //点击取消的回调
        const onClose = () => {
            this.clearCheckEvent();
        }
        if (item.type == 1) {
            WfForm.getGlobalStore().setTabKey(item.key);
            this.renderTabPage(comType, state)
        } else {
            window.historyRoute.push({
                pathname: "/req/odocComs",
                state,
                workflowStores,
                onClose
            });
        }


    };

    renderTabPage(comType, otherParams) {
        const workflowStores = this.getWorkflowStores();
        const {wfGlobalStore, wfOperateStore} = workflowStores;

        this.resetContainer(() => {
            // const comType = pageTypes.ODOC_LOG_LIST;

            const params = {comType, ...otherParams};
            const props = {
                comType,
                workflowStores,
                params
            }
            const com = <coms.OdocPages {...props}/>

            ReactDOM.render(com, this.containerInForm);
        })
    }

    /**
     * 加载自定义的页面
     */
    resetContainer(callback) {
        const tabContainer = document.getElementsByClassName("wf-append-iframe");

        if (tabContainer && tabContainer.length > 0) {
            const containerInForm = this.containerInForm;
            if (containerInForm) {
                ReactDOM.unmountComponentAtNode(containerInForm);
            } else {
                this.containerInForm = document.createElement("div");
                this.containerInForm.setAttribute("id", "odoc_custab_box");
                tabContainer[0].appendChild(this.containerInForm);
            }
            this.safeExecuteFunc(callback);
        } else {
            window.setTimeout(() => {
                this.resetContainer(callback);
            }, 300);
        }
    }

    /**
     * 公文流转
     */
    doOdocTransfer() {
        const workflowStores = this.getWorkflowStores();
        const {wfGlobalStore, wfOperateStore} = workflowStores;

        const callbackFn = (callback, funcParams) => {
            const dialogType = 1;
            const comType = pageTypes.ODOC_TRANSFER_DIALOG;

            /**
             * 这个标签要注意，因此当前文件是直接引入到流程的，此时公文的标签
             * 还未加载，所以目前的这个标签，需要加入到流程模块，才能保证正常显示
             */
            const title = getLabel('518550', '公文流转');
            const state = {dialogType, title, comType};

            //保存成功后的回调
            const submitCallBack = (isend, data) => {
                const {commonParam} = wfGlobalStore;
                const {submitParam} = wfOperateStore;

                const {f_weaver_belongto_userid, f_weaver_belongto_usertype} = commonParam;
                const {requestid} = submitParam;
                if (isend === "1") {     //关闭流程表单
                    callback();
                } else {        //刷新流程表单
                    WfForm.reloadPage({requestid, f_weaver_belongto_userid, f_weaver_belongto_usertype});
                }
            }

            //点击取消的回调
            const onClose = () => {
                this.clearCheckEvent();
            }

            window.historyRoute.push({
                pathname: "/req/odocComs",
                state,
                workflowStores,
                callback: submitCallBack,
                onClose
            });
        }

        //先保存流程表单
        this.doSaveWorkflow(callbackFn, true);
    }

    //撤回
    withdraw() {
        const workflowStores = this.getWorkflowStores();
        const {wfGlobalStore, wfOperateStore} = workflowStores;
        const dialogType = 1;
        const comType = pageTypes.ODOC_WITHDRAW_DIALOG;
        const title = getLabel(32025, "撤回");
        const state = {dialogType, comType, title}
        //保存成功后的回调
        const submitCallBack = (data) => {
            if (data) {
                var api_status = data.api_status;
                var verifyRight = data.verifyRight;
                if (api_status) {
                    if (verifyRight) {
                        //有权限刷新
                        const {commonParam} = wfGlobalStore;
                        const {submitParam} = wfOperateStore;
                        const {f_weaver_belongto_userid, f_weaver_belongto_usertype} = commonParam;
                        const {requestid} = submitParam;
                        WfForm.reloadPage({requestid, f_weaver_belongto_userid, f_weaver_belongto_usertype});
                    } else {
                        //关闭表单 表单操作完成后返回到源页面
                        window.returnSourcePage && window.returnSourcePage();
                        // this.doSaveWorkflow(function(ck){if(typeof ck == "function"){ck()}})
                    }
                }
            }
        }
        window.historyRoute.push({
            pathname: "/req/odocComs",
            state,
            workflowStores,
            callback: submitCallBack,
        });
    }

    //管理员撤回
    withdrawManager(customname) {
        const workflowStores = this.getWorkflowStores();
        const {wfGlobalStore, wfOperateStore} = workflowStores;

        const dialogType = 1;
        const comType = pageTypes.ODOC_WITHDRAW_MANAGER_DIALOG;
        let title = customname || getLabel(32025, "撤回");
        const state = {dialogType, comType, title}
        //保存成功后的回调
        const submitCallBack = (data) => {
            if (data) {
                var api_status = data.api_status;
                var verifyRight = data.verifyRight;
                if (api_status) {
                    if (verifyRight) {
                        //有权限刷新
                        const {commonParam} = wfGlobalStore;
                        const {submitParam} = wfOperateStore;
                        const {f_weaver_belongto_userid, f_weaver_belongto_usertype} = commonParam;
                        const {requestid} = submitParam;
                        WfForm.reloadPage({requestid, f_weaver_belongto_userid, f_weaver_belongto_usertype});
                    } else {
                        //关闭表单
                        window.returnSourcePage && window.returnSourcePage();
                        // this.doSaveWorkflow(function(ck){if(typeof ck == "function"){ck()}})
                    }
                }
            }

        }
        window.historyRoute.push({
            pathname: "/req/odocComs",
            state,
            workflowStores,
            callback: submitCallBack,
        });
    }

    //加/减签
    updateOperator() {
        const workflowStores = this.getWorkflowStores();
        const dialogType = 1;
        const comType = pageTypes.ODOC_UPDATEOPERATOR_DIALOG;
        const title = getLabel(130106, "加减签");
        const state = {dialogType, comType, title}
        window.historyRoute.push({
            pathname: "/req/odocComs",
            state,
            workflowStores
        });
    }

    /**
     * 代录意见
     */
    appendOdocLog() {
        const workflowStores = this.getWorkflowStores();
        const dialogType = 1;
        const comType = pageTypes.ODOC_APPEND_SIGNLOG;
        const title = getLabel(520456, "代录意见");
        const state = {dialogType, title, comType}
        const {wfSignListStore} = workflowStores;

        //保存成功后的回调
        const submitCallBack = (isend, data) => {
            const {updateLogParams} = wfSignListStore;
            const reloadLogListParams = {pgnumber: 1, atmet: '', maxrequestlogid: 0};
            updateLogParams(reloadLogListParams, true);
        }

        window.historyRoute.push({
            pathname: "/req/odocComs",
            state,
            workflowStores,
            callback: submitCallBack,
        });
    }

    /**
     * 为自己追加意见
     */
    appendOdocLogSelf() {
        const workflowStores = this.getWorkflowStores();
        const dialogType = 1;
        const comType = pageTypes.ODOC_APPEND_SIGNLOG_SELF;
        const title = getLabel(519035, "追加意见");
        const state = {dialogType, title, comType}
        const {wfSignListStore} = workflowStores;

        //保存成功后的回调
        const submitCallBack = (isend, data) => {
            const {updateLogParams} = wfSignListStore;
            const reloadLogListParams = {pgnumber: 1, atmet: '', maxrequestlogid: 0};
            updateLogParams(reloadLogListParams, true);
        }

        window.historyRoute.push({
            pathname: "/req/odocComs",
            state,
            workflowStores,
            callback: submitCallBack,
        });
    }

    /**
     * 修改意见
     */
    updateOdocLog() {
        const workflowStores = this.getWorkflowStores();
        const dialogType = 1;
        const comType = pageTypes.ODOC_UPDATE_SIGNLOG;
        const title = getLabel(132410, "修改意见");
        const state = {dialogType, title, comType}

        const {wfSignListStore} = workflowStores;
        //保存成功后的回调
        const submitCallBack = (isend, data) => {
            const {updateLogParams} = wfSignListStore;
            const reloadLogListParams = {pgnumber: 1, atmet: '', maxrequestlogid: 0};
            updateLogParams(reloadLogListParams, true);
        }
        window.historyRoute.push({
            pathname: "/req/odocComs",
            state,
            workflowStores,
            callback: submitCallBack,
        });
    }

    viewTransferChangeLog() {
        const workflowStores = this.getWorkflowStores();
        const dialogType = 1;
        const comType = pageTypes.ODOC_ADJUST_LOG;
        const title = getLabel(25990, "调整日志");
        const state = {dialogType, title, comType}

        //保存成功后的回调
        window.historyRoute.push({
            pathname: "/req/odocComs",
            state,
            workflowStores
        });
    }

    /**
     * 流程跟踪
     */
    doFollowRequest(flag) {
        const workflowStores = this.getWorkflowStores();
        const {wfOperateStore, wfGlobalStore} = workflowStores;
        const {submitParam, loadRightMenu} = wfOperateStore;
        const {commonParam} = wfGlobalStore;
        const {requestid} = submitParam;
        const {f_weaver_belongto_userid, f_weaver_belongto_usertype} = commonParam;

        if (requestid && requestid > 0) {
            if (flag == 1) {
                odocRequestAPI.doFollowRequest({
                    requestid,
                    f_weaver_belongto_userid,
                    f_weaver_belongto_usertype
                }).then(data => {
                    if (data.api_status && data.api_status == true) {
                        Toast.success(`${getLabel(131972, "流程跟踪")}${getLabel(15242, "成功")}`);
                        loadRightMenu(commonParam)

                    } else {
                        Toast.fail(`${getLabel(131972, "流程跟踪")}${getLabel(498, "失败")}`);
                    }
                    this.clearCheckEvent();
                })
            } else {
                odocRequestAPI.removeFollowRequest({
                    requestid,
                    f_weaver_belongto_userid,
                    f_weaver_belongto_usertype
                }).then(data => {
                    if (data.api_status && data.api_status == true) {
                        Toast.success(`${getLabel(201, "取消")}${getLabel(131972, "流程跟踪")}${getLabel(15242, "成功")}`);
                        loadRightMenu(commonParam)
                    } else {
                        Toast.fail(`${getLabel(201, "取消")}${getLabel(131972, "流程跟踪")}${getLabel(498, "失败")}`);
                    }
                    this.clearCheckEvent();
                })
            }

        }
    };

    /**
     * 结束本人处理确认回调
     */
    doEndMyRequestConfirm(data, callback) {
        let _that = this;
        const workflowStores = this.getWorkflowStores();
        const {wfOperateStore, wfGlobalStore} = workflowStores;
        const {commonParam = {}, baseParam = {}} = wfGlobalStore;
        const {workflowid, nodeid} = commonParam;
        const {submitParam} = wfOperateStore;
        const {requestid} = submitParam;
        const isDrawEnd = data.isEndPerson ? 1 : 0;
        const {f_weaver_belongto_userid, f_weaver_belongto_usertype} = baseParam;

        let remark = window.WfForm.getSignRemark();
        let params = {
            isend: 1,
            workflowid,
            nodeid,
            requestid,
            remark,
            isDrawEnd,
            f_weaver_belongto_userid,
            f_weaver_belongto_usertype
        };

        odocRequestAPI.doEndPersonTreat(params).then(data1 => {
            if (data1.api_status && data1.api_status == true) {
                callback();
                wfOperateStore.controllBottomBtnDisable(false);
            } else {
                Toast.fail(getLabel(30651, "操作失败"), 1);
                wfOperateStore.controllBottomBtnDisable(false);
                _that.clearCheckEvent();
            }
        })
    }

    /**
     * 结束本人处理
     */
    doEndMyRequest() {
        const workflowStores = this.getWorkflowStores();
        const {wfOperateStore, wfGlobalStore} = workflowStores;
        const {commonParam = {}, baseParam = {}} = wfGlobalStore;
        const {workflowid, nodeid} = commonParam;
        const {submitParam} = wfOperateStore;
        const {requestid} = submitParam;
        const {f_weaver_belongto_userid, f_weaver_belongto_usertype} = baseParam;
        let _that = this;
        let callbackFun = function (callback) {
            wfOperateStore.controllBottomBtnDisable(true);
            odocRequestAPI.isEndTreatPerson({
                requestid,
                f_weaver_belongto_userid,
                f_weaver_belongto_usertype
            }).then(data => {
                if (data.api_status && data.api_status == true) {

                    let msg = "";
                    if (data.isEndPerson == true) {
                        msg = getLabel(519952, "您是此公文的唯一办理人员，确定要把文件送归档员存档吗？");
                    } else {
                        msg = getLabel(519953, "您确认结束本人处理吗？");
                    }
                    showConfirm({
                        content: msg,
                        cancelEvent: () => {
                            wfOperateStore.controllBottomBtnDisable(false);
                            _that.clearCheckEvent();
                        },
                        okEvent: () => {
                            _that.doEndMyRequestConfirm(data, callback)
                        }
                    })
                }
            })
        };
        this.doSaveWorkflow(callbackFun, true);
    };

    /**
     * 转文
     */
    changeOdocType() {
        const workflowStores = this.getWorkflowStores();
        const {wfGlobalStore, wfOperateStore} = workflowStores;

        const callbackFn = (callback, funcParams) => {
            const comType = pageTypes.ODOC_CHANGE_ODOC_TYPE_DIALOG;
            const dialogType = 1;
            const state = {dialogType, comType}
            //点击取消的回调
            const onClose = () => {
                this.clearCheckEvent();
            }

            window.historyRoute.push({
                pathname: "/req/odocComs",
                state,
                workflowStores,
                onClose
            });
        }

        //先保存流程表单
        this.doSaveWorkflow(callbackFn);
    }

    doForceArchive() {
        const confirmEvent = () => {
            const workflowStores = this.getWorkflowStores();
            const {wfOperateStore, wfGlobalStore} = workflowStores;
            const {commonParam = {}} = wfGlobalStore;
            const {workflowid, nodeid, f_weaver_belongto_userid, f_weaver_belongto_usertype} = commonParam;
            const {submitParam} = wfOperateStore;
            const {requestid} = submitParam;

            //先执行保存后进行结束本人处理
            const remark = WfForm.getSignRemark();

            const params = {
                workflowid,
                nodeid,
                requestid,
                f_weaver_belongto_userid,
                f_weaver_belongto_usertype,
                remark
            };

            odocRequestAPI.forceArchive(params).then(data => {
                const {success} = data;

                if (success) {
                    try {
                        window.returnSourcePage();
                    } catch (e) {
                    }
                } else {
                    const {msg = getLabel(30651, "操作失败")} = data;
                    Toast.fail(msg, 1);
                }
            })
        }

        showConfirm({
            content: getLabel(131982, "是否强制归档此流程"),
            cancelEvent: () => {
            },
            okEvent: confirmEvent.bind(this)
        });
    }
}